﻿using Corina.Commands;
using Corina.Common;
using Corina.Cydee.DataService;
using Corina.Datamodel.DataObject;
using Corina.Datamodel.Entities;
using Corina.Enumerations;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Printing;
namespace Corina.Cydee.Apphub.Viewmodels
{
    public class DeviceMeasureViewmodel : ViewmodelBase
    {
        public DeviceMeasureViewmodel()
        {
            DeviceMeasureClient.ChangeDeviceMeasureAvailabilityCompleted += ChangeDeviceMeasureAvailabilityCompleted;
            DeviceMeasureClient.GetAllDeviceMeasureCompleted += GetAllDeviceMeasureCompleted;
            DeviceMeasureClient.RemoveDeviceMeasureCompleted += RemoveDeviceMeasureCompleted;
            DeviceClient.GetDeviceKindItemsCompleted += GetDeviceKindItemsCompleted;
            if (DataContext.IsValid)
            {
                LoadRelatedData();
                LoadData();
            }
        }

        private void GetDeviceKindItemsCompleted(object sender, GetDeviceKindItemsCompletedEventArgs e)
        {
            if(e.Error == null)
            {
                DeviceKindCollection = new ObservableCollection<DeviceKindInfo>(e.Result.Entities.OfType<DeviceKindInfo>());
            }
        }

        #region Methods
        private void RemoveDeviceMeasureCompleted(object sender, RemoveDeviceMeasureCompletedEventArgs e)
        {
            LoadData();
        }

        private void GetAllDeviceMeasureCompleted(object sender, GetAllDeviceMeasureCompletedEventArgs e)
        {
            if(e.Error == null)
            {
                if (e.Result.Result == ResultValue.Succeed)
                {
                    var items = (from t in e.Result.DataObjects
                                 select new
                                 {
                                     ItemIndex = t["ROW_NUMBER"],
                                     Id = t["Id"],
                                     DeviceSn = (string)t["DeviceSn"],
                                     Kind = (string)t["Kind"],
                                     ProofValue = t["ProofValue"],
                                     Name = t["Name"],
                                     Density = (double)t["Density"],
                                     Temperature = (double)t["Temperature"],
                                     Humidity = (double)t["Humidity"],
                                     Tester = (string)t["Tester"],
                                     TransType = (TransTypeValue)Convert.ToInt32(t["TransType"]),
                                     TestTime = Convert.ToDateTime(t["TestTime"]),
                                     IsOpen = Convert.ToBoolean(t["IsOpen"]),
                                     UserName = t["UserName"],
                                     MobileOrIP = t["MobileOrIP"]
                                 });
                    ItemsCollection = new ObservableCollection<object>(items);
                    ItemsCount = e.Result.TotalCount;
                }
            }
            IsBusy = false;
        }


        private void ChangeDeviceMeasureAvailabilityCompleted(object sender, ChangeDeviceMeasureAvailabilityCompletedEventArgs e)
        {
            LoadData();
        }

        protected override void LoadData(params object[] paras)
        {
            IsBusy = true;
            DeviceMeasureClient.GetAllDeviceMeasureAsync(Account, Password, DeviceSn, KindId, UserId, MeasureName, OnlyOpen, Index, 20);
        }

        private void LoadRelatedData()
        {
            DeviceClient.GetDeviceKindItemsAsync();
        }
        #endregion

        #region Collection
        private ObservableCollection<DeviceKindInfo> _deviceKindCollection;
        public ObservableCollection<DeviceKindInfo> DeviceKindCollection
        {
            get { return _deviceKindCollection; }
            set
            {
                _deviceKindCollection = value;
                RaisePropertyChanged(() => DeviceKindCollection);
            }
        }

        private ObservableCollection<object> _itemsCollection;
        public ObservableCollection<object> ItemsCollection
        {
            get { return _itemsCollection; }
            set
            {
                _itemsCollection = value;
                RaisePropertyChanged(() => ItemsCollection);
            }
        }
        #endregion

        #region Search
        private string _keywords = string.Empty;
        public string Keywords
        {
            get { return _keywords; }
            set
            {
                _keywords = value;
                RaisePropertyChanged(() => Keywords);
            }
        }

        private string _deviceSn = string.Empty;
        public string DeviceSn
        {
            get { return _deviceSn; }
            set
            {
                _deviceSn = value;
                RaisePropertyChanged(() => DeviceSn);
            }
        }

        private int _userId = 0;
        public int UserId
        {
            get { return _userId; }
            set
            {
                _userId = value;
                RaisePropertyChanged(() => UserId);
            }
        }

        private DeviceKindInfo _selectedDeviceKind;
        public DeviceKindInfo SelectedDeviceKind
        {
            get { return _selectedDeviceKind; }
            set
            {
                _selectedDeviceKind = value;
                RaisePropertyChanged(() => SelectedDeviceKind);
                KindId = SelectedDeviceKind == null ? 0 : SelectedDeviceKind.Id;
            }
        }

        private int _kindId = 0;
        public int KindId
        {
            get { return _kindId; }
            set
            {
                _kindId = value;
                RaisePropertyChanged(() => KindId);
            }
        }

        private string _measureName = string.Empty;
        public string MeasureName
        {
            get { return _measureName; }
            set
            {
                _measureName = value;
                RaisePropertyChanged(() => MeasureName);
            }
        }

        private bool _onlyOpen = false;
        public bool OnlyOpen
        {
            get { return _onlyOpen; }
            set
            {
                _onlyOpen = value;
                RaisePropertyChanged(() => OnlyOpen);
                Index = 1;
                LoadData();
            }
        }
        #endregion

        #region Command
        public ICommand LoadCommand
        {
            get
            {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate {
                        Index = 1;
                        LoadData();
                    }
                };
            }
        }

        public ICommand RemoveCommand
        {
            get {
                return new DelegateCommand(t =>
                {
                    int id = Convert.ToInt32(t);

                    if(ShowConfirm(Language.LanguageKeys.IDS_DELETE_CONFIRM)== MessageBoxResult.OK)
                    {
                        DeviceMeasureClient.RemoveDeviceMeasureAsync(Account, Password, id);
                    }

                });
            }
        }

        public ICommand SetOpenCommand
        {
            get
            {
                return new DelegateCommand(t =>
                {
                    int id = Convert.ToInt32(t);

                    DeviceMeasureClient.ChangeDeviceMeasureAvailabilityAsync(Account, Password, id, true);
                });
            }
        }

        public ICommand SetHideCommand
        {
            get
            {
                return new DelegateCommand(t =>
                {
                    int id = Convert.ToInt32(t);

                    DeviceMeasureClient.ChangeDeviceMeasureAvailabilityAsync(Account, Password, id, false);
                });
            }
        }

        public ICommand ShowPrintCommand
        {
            get
            {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate {
                        ShowPrintPreview();
                    }
                };
            }
        }

        public ICommand ClosePrintCommand
        {
            get
            {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate {
                        ShowPrintDialog = false;
                    }
                };
            }
        }

        public ICommand PrintCommand
        {
            get
            {
                return new DelegateCommand(t =>
                {
                    PrintUIElement = t as UIElement;
                    PrintDocument printDoc = new PrintDocument();
                    printDoc.PrintPage += PrintPage;
                    printDoc.BeginPrint += BeginPrint;
                    printDoc.EndPrint += EndPrint;
                    printDoc.Print("Measure Report");
                });
            }
        }

        #endregion

        #region Print
        private bool _showDataOption = false;
        public bool ShowDataOption
        {
            get { return _showDataOption; }
            set
            {
                _showDataOption = value;
                RaisePropertyChanged(() => ShowDataOption);
            }
        }

        private bool _printing = false;
        public bool Printing
        {
            get { return _printing; }
            set
            {
                _printing = value;
                RaisePropertyChanged(() => Printing);
            }
        }

        private UIElement _printUIElement;
        public UIElement PrintUIElement
        {
            get { return _printUIElement; }
            set
            {
                _printUIElement = value;
                RaisePropertyChanged(() => PrintUIElement);
            }
        }

        private bool _showPrintDialog = false;
        public bool ShowPrintDialog
        {
            get { return _showPrintDialog; }
            set
            {
                _showPrintDialog = value;
                RaisePropertyChanged(() => ShowPrintDialog);
            }
        }

        public string AccountName
        {
            get { return DataContext.IsValid ? DataContext.CurrentAccount.Name : ""; }
        }

        public string RoleName
        {
            get { return DataContext.IsValid ? DataContext.CurrentRole.Name : ""; }
        }

        private void ShowPrintPreview()
        {
            ShowPrintDialog = true;

        }

        private void EndPrint(object sender, EndPrintEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.Message);
            }
            Printing = false;
            PrintUIElement = null;
            
        }

        private void BeginPrint(object sender, BeginPrintEventArgs e)
        {
            Printing = true;
        }

        private void PrintPage(object sender, PrintPageEventArgs e)
        {
            //e.HasMorePages = true;
            e.PageVisual = PrintUIElement;
            //e.HasMorePages = true;
        }
        #endregion
    }
}
